//
//  UIViewController+PresentViewControllerOnIOS13.m
//  JQLive
//
//  Created by Bruce on 2020/8/5.
//  Copyright © 2020 mlqk. All rights reserved.
//

#import <objc/runtime.h>

#import "UIViewController+PresentViewControllerOnIOS13.h"

@implementation UIViewController (PresentViewControllerOnIOS13)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

-(void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion{
    @try {
        
        //分类重写原类方法时, 类的方法列表, 分类的冲洗会排在前边, 原方法会排在最后. 执行时, 只有第一个会响应, 即原方法不会响应, 我们想要执行原方法, 无法使用super, 需要遍历原类的方法列表, 找到最后一个同名方法(即原方法), 然后获取方法的指针并执行
        
        viewControllerToPresent.modalPresentationStyle = UIModalPresentationFullScreen;
        
        u_int count;
        
        Method *methodsArr = class_copyMethodList([UIViewController class], &count);
        NSInteger index = 0;
        //NSLog(@"methodName begin----------------------------------------");
        for (int i = 0; i < count; i++) {
            SEL method = method_getName(methodsArr[i]);
            NSString *methodName = [NSString stringWithCString:sel_getName(method) encoding:NSUTF8StringEncoding];
            //NSLog(@"%@",methodName);
            if ([methodName isEqualToString:@"presentViewController:animated:completion:"]) {
                index = i;
                NSLog(@"methodName get ---> %d",i);
            }
        }
        //NSLog(@"methodName end----------------------------------------");
        
        SEL sel = method_getName(methodsArr[index]);
        IMP imp = method_getImplementation(methodsArr[index]);
        
        ((void (*)(id, SEL, id, BOOL, id))imp)(self, sel, viewControllerToPresent, flag, completion);
        
    } @catch (NSException *exception) {
        NSLog(@"presentViewController error %@",exception);
    }
}

#pragma clang diagnostic pop

@end
